package com.hunan.api.catv.service.biz.mq;

import com.hunan.api.catv.entity.ServiceResult;
import com.hunan.api.catv.service.ResultService;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MqBiz extends ResultService {

    @Autowired
    AmqpTemplate amqpTemplate;


    @Autowired
    private RabbitTemplate rabbitTemplate;


    public ServiceResult pushFANOUT(String exchange, Object message) {
        try {

            amqpTemplate.convertAndSend(exchange, null, message);
        } catch (Exception e) {
            log.error("{}", e);
            return buildFail("");
        }
        return buildOK(true);
    }


    public ServiceResult push(String exchange, String key, Object message) {
        try {

            amqpTemplate.convertAndSend(exchange, key, message);
        } catch (Exception e) {
            log.error("{}", e);
            return buildFail("");
        }
        return buildOK(true);
    }

    public ServiceResult pushAndConfirm(String exchange, String key, Object message,String confirmId) {
        try {
            CorrelationData correlationData = new CorrelationData(confirmId);
            rabbitTemplate.convertAndSend(exchange, key, message,correlationData);
        } catch (Exception e) {
            log.error("{}", e);
            return buildFail("");
        }
        return buildOK(true);
    }

    public ServiceResult delayPush(String exchange, String key, Object message, Long time) {
        try {
            amqpTemplate.convertAndSend(exchange, key, message, new MessagePostProcessor() {
                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    message.getMessageProperties().setHeader("x-delay", time);
                    return message;
                }
            });
        } catch (Exception e) {
            log.error("{}", e);
            return buildFail("");
        }
        return buildOK(true);
    }

}
